<template>
	<view class="leader-center">
		<view class="leader-header">
			<view class="top-line">
				<view class="flex col--center ">
					<image class="icon-avatar m-r-10" :src="userInfo.avatar" />
					<text>{{leaderInfo.name}}</text>
				</view>
				<router-link to="/bundle/pages/user_wallet/user_wallet">
					<view class="withdraw flex row-between">
						<text>{{$zhTran('提现')}}</text>
						<text>></text>
					</view>
				</router-link>
			</view>
			<view class="center-num m-b-20">
				<view class="title m-b-10">{{$zhTran('待提现(元)')}}</view>
				<view class="num">{{leaderInfo.visible_balance}}</view>
			</view>
			<view class="footer-box flex row-around">
				<view class="box-item">
					<view class="title m-b-10">{{$zhTran('我的收入(元)')}}</view>
					<view class="num">{{leaderInfo.leader_profit}}</view>
				</view>
				<view class="line"></view>
				<view class="box-item">
					<view class="title m-b-10">{{$zhTran('待核销订单')}}</view>
					<view class="num">{{leaderInfo.wait_verification}}</view>
				</view>
			</view>
		</view>
		<view class="order-nav flex m-t-20">
			<router-link class="nav-item" to="/bundle2/pages/community_group_purchase/leader/order_list">
				<view class="flex-col col-center">
					<u-icon name="order" size="48" color="rgba(252, 185, 52, 1)" />
					<view class="xs m-t-12">{{$zhTran('我的订单')}}</view>
				</view>
			</router-link>
			<view class="nav-item" @click="verificationShow=true">
				<view class="flex-col col-center">
					<u-icon name="scan" size="48" color="rgba(252, 185, 52, 1)" />
					<view class="xs m-t-12">{{$zhTran('订单核销')}}</view>
				</view>
			</view>
			<router-link class="nav-item" to="/bundle2/pages/community_group_purchase/leader/leader_address">
				<view class="flex-col col-center">
					<u-icon name="map" size="48" color="rgba(252, 185, 52, 1)" />
					<view class="xs m-t-12">{{$zhTran('我的地址')}}</view>
				</view>
			</router-link>
		</view>
		<view class="tabs-swiper m-t-20">
			<u-tabs-swiper ref="tabs" :list="tabsList" :current="tabsIndex" :is-scroll="false" active-color="#FFD000"
				bar-width="60" :bold="false" @change="changeCurrentTab">
			</u-tabs-swiper>
		</view>
		<view class="activity-list">
			<mescroll-uni ref="mescrollRef" :fixed="false" :up="{
				  auto: false,
				  noMoreSize: 3,
				  empty: {
				  	icon: $getImageUri('resource/image/shopapi/uniapp/empty/order.png'),
				  	tip: $zhTran('暂无团购活动~'),
				  	fixed: true
				  }
			  }" :down="{ auto: false }" @init="mescrollInit" @down="downCallback" @up="upCallback">
				<block v-for="(tabItem, tabIndex) in tabsList" :key="tabItem['sign']">
					<view class="order-contain" v-if="currentTab['sign'] === tabItem['sign']">
						<view class="order" v-for="orderItem in tabsList[tabIndex].list" :key="orderItem.id"
							@tap="goActivityDetail(orderItem.id)">
							<view class="top-item">
								<view class="title">{{orderItem.name}}</view>
								<view class="date">
									<u-icon name="clock" size="28"
										class="m-r-5" />{{orderItem.end_time}}{{$zhTran('结束')}}
								</view>
								<view class="status" v-if="orderItem.status==0">{{$zhTran('未开始')}}</view>
								<view class="status work" v-if="orderItem.status==1">{{$zhTran('进行中')}}</view>
								<view class="status end" v-if="orderItem.status==2">{{$zhTran('已结束')}}</view>
							</view>
							<view class="goods m-t-20">
								<image :src="goodsItem.goods_image" v-for="(goodsItem,gidx) in orderItem.goods"
									:key="gidx" mode="widthFix"></image>
							</view>
							<view class="flex row-between m-t-20 m-b-20">
								<view>{{$zhTran('订单实付金额')}}：<text
										style="color:rgba(250, 64, 52, 1)">￥{{orderItem.order_amount}}</text>
								</view>
								<view class="sm muted">{{$zhTran('共'+orderItem.goods_count+'件商品')}}<u-icon
										name="arrow-right"></u-icon>
								</view>
							</view>
							<u-divider half-width="100%" :use-slot="false"></u-divider>
							<view class="flex row-right m-t-20" @click.native.stop="shareActivity(orderItem)">
								<button class="share-btn">{{$zhTran('分享')}}</button>
							</view>
						</view>
					</view>
				</block>
			</mescroll-uni>

			<u-popup v-model="verificationCodeShow" mode="center" width="80%">
				<view class="verification-code">
					<view class="title flex col--center row-center">{{$zhTran('请输入订单核销码')}}</view>
					<view class="text">
						<u-input :placeholder="$zhTran('请输入11位核销码')" border :value="verification_code"
							@input="inputVerificationCode"></u-input>
					</view>
					<view class="flex btns">
						<view class="confirm p-20" @click="verificationOrder(verification_code)">{{$zhTran('确定')}}
						</view>
						<view class="cancel p-20" @click="cancel">{{$zhTran('取消')}}</view>
					</view>
				</view>
			</u-popup>

			<u-popup v-model="sharePosterVisible" mode="center" width="90%">
				<activity-poster ref="posterActivity" :leader="optionsActivity.leader" :options="optionsActivity"
					:activity="optionsActivity.activity" @success="handleSuccess" @complete="handleComplete" />
				<view class="share-btns flex row-between m-t-20">
					<view class="share" @click="saveImageToOther">{{$zhTran('转发好友')}}</view>
					<view class="saveImg" @click="saveImageToAlbum">{{$zhTran('点击保存到相册')}}</view>
				</view>
			</u-popup>
		</view>
		<u-action-sheet-circle :list="list" :tips="tips" v-model="verificationShow" @click="actionSheet">
		</u-action-sheet-circle>
		<loading-view v-show="loading"></loading-view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import {
		apiMnpCgpQrCode
	} from "@/api/app";
	import {
		baseURL,
		basePath
	} from '@/config/app'
	import {
		apiCommunityGroupPurchaseLeaderActivityList,
		apiCommunityGroupPurchaseLeaderDetail,
	} from "@/api/community_group_purchase"
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins";
	import activityPoster from "@/bundle2/pages/community_group_purchase/poster/activity_poster.vue";
	export default {
		mixins: [MescrollMixin],
		components: {
			activityPoster
		},

		data() {
			return {
				verification_code: '',
				verificationCodeShow: false,
				tips: {
					text: this.$zhTran('请选择订单核销方式'),
					color: 'rgba(56, 56, 56, 1)',
					fontSize: 28,
				},
				list: [{
					text: this.$zhTran('直接核销'),
					color: 'rgba(56, 56, 56, 1)',
					fontSize: 28,
					icon: 'checkmark-circle',
					iconColor: '#fff',
					iconSize: 32,
					iconBgColor: 'rgba(255, 141, 26, 1)',
					iconBgSize: 64,
					iconCircleColor: '#fff6ed',
					iconCircleSize: 138,
				}, {
					text: this.$zhTran('扫码核销'),
					color: 'rgba(56, 56, 56, 1)',
					fontSize: 28,
					icon: 'scan',
					iconSize: 32,
					iconColor: '#fff',
					iconBgColor: 'rgba(64, 115, 250, 1)',
					iconBgSize: 64,
					iconCircleColor: '#f2f6ff',
					iconCircleSize: 138,
				}, {
					text: this.$zhTran('输入核销码'),
					color: 'rgba(56, 56, 56, 1)',
					fontSize: 28,
					icon: 'edit-pen',
					iconSize: 32,
					iconColor: '#fff',
					iconBgColor: 'rgba(51, 175, 41, 1)',
					iconBgSize: 64,
					iconCircleColor: '#eff9ee',
					iconCircleSize: 138,
				}],
				verificationShow: false,
				tabsList: [{
					sign: 'all',
					name: this.$zhTran('全部'),
					status: '',
					count: '',
					list: [],
				}, {
					sign: 'not',
					name: this.$zhTran('未开始'),
					status: '0',
					count: '',
					list: [],
				}, {
					sign: 'work',
					name: this.$zhTran('进行中'),
					status: '1',
					count: '',
					list: [],
				}, {
					sign: 'end',
					name: this.$zhTran('已结束'),
					status: '2',
					count: '',
					list: [],
				}],
				tabsIndex: '',
				leaderInfo: [],
				sharePosterVisible: false,
				optionsActivity: {
					leader: {},
					activity: {},
					qr_code: ''
				},
				imgPath: '',
				loading: true,
			}
		},
		computed: {
			currentTab() {
				return this.tabsList[this.tabsIndex] || {}
			},
			mapTabsItem() {
				return sign => this.tabsList.find(item => item['sign'] === sign)
			}
		},
		methods: {
			...mapActions(['getUser']),
			changeCurrentTab(index) {
				this.tabsIndex = index
				this.refreshOrderData()
			},
			refreshOrderData() {
				this.$nextTick(() => {
					this.mescroll.resetUpScroll()
				})
			},
			// 上拉加载更多
			upCallback({
				num,
				size
			}) {
				const sign = this.currentTab.sign
				apiCommunityGroupPurchaseLeaderActivityList({
					status: this.currentTab.status,
					page_no: num,
					page_size: size,
				}).then(({
					lists,
					count,
					extend
				}) => {
					const tab = this.mapTabsItem(sign)
					if (num === 1) tab.list = []
					tab.list = [...tab.list, ...lists]
					tab.list = this.$zhTran(tab.list)
					this.mescroll.endSuccess(lists.length, count)
				}).catch(err => {
					this.mescroll.endErr()
				})
			},

			// 去活动详情
			goActivityDetail(id) {
				this.$Router.push({
					path: '/bundle2/pages/community_group_purchase/leader/activity_detail',
					query: {
						cgp_id: id
					}
				})
			},
			actionSheet(event) {
				if (event === 0) {
					// 直接核销
					this.$Router.push({
						path: '/bundle2/pages/community_group_purchase/leader/order_list',
					})
				} else if (event === 1) {
					// 扫码核销
					this.scanCode();
				} else if (event === 2) {
					// 输入核销码
					this.verification_code = ''
					this.verificationCodeShow = true;
				}
			},
			scanCode() {
				var that = this,
					themeColor = this.themeColor
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success(res) {
						uni.showModal({
							content: this.$zhTran('确定核销该订单？'),
							confirmColor: themeColor,
							confirmText: this.$zhTran('确定'),
							success(res2) {
								if (res2.confirm) {
									that.verificationOrder(res.result)
								}
							}
						})
					},
					fail(res) {
						console.log(res)
						// app.alertModal('调用摄像头失败', 2)
					}
				})
			},
			inputVerificationCode(val) {
				this.verification_code = val
			},
			cancel() {
				this.verificationCodeShow = false
				this.verification_code = ''
			},
			verificationOrder(code) {
				console.log('code', code)
				if (code == '') {
					this.$toast({
						title: this.$zhTran('请填写核销码')
					})
					return
				}
				this.verificationCodeShow = false
			},
			shareActivity(row) {
				this.loading = true
				this.optionsActivity.leader = {
					name: this.leaderInfo.name,
					user_info: {
						avatar: this.userInfo.avatar
					}
				}
				this.optionsActivity.activity = row
				this.optionsActivity = this.$zhTran(this.optionsActivity)
				console.log(this.optionsActivity)
				this.getPoster(row.id)
			},
			async getPoster(cgp_id) {
				try {
					const res = await Promise.all([
						// #ifdef MP-WEIXIN
						apiMnpCgpQrCode({
							cgp_id,
							leader_id: this.leaderInfo.id
						})
						// #endif
					]);
					console.log('res', res)
					// #ifdef MP-WEIXIN
					this.optionsActivity.qr_code = res[0]?.qr_code;
					// #endif
					this.$nextTick(() => {
						this.$refs.posterActivity.drawCanvas();
					})
				} catch (e) {
					this.$toast({
						title: e,
					});
				} finally {
					this.loading = false
				}
			},
			handleSuccess(val) {
				console.log('handleSuccess', this.imgPath)
				this.imgPath = val;
				this.sharePosterVisible = true
				this.loading = false
			},
			handleComplete() {
				console.log('handleComplete')
				this.loading = false
			},
			saveImageToOther() {
				console.log('imgPath', this.imgPath)
				uni.showShareImageMenu({
					path: this.imgPath
				})
			},
			saveImageToAlbum() {
				// #ifndef H5
				uni.saveImageToPhotosAlbum({
					filePath: this.imgPath,
					success: (res) => {
						this.$toast({
							title: this.$zhTran("保存成功"),
						});
					},
					fail: (err) => {
						this.$toast({
							title: this.$zhTran("保存失败"),
						});
					},
				});
				// #endif
				// #ifdef H5
				this.$toast({
					title: this.$zhTran("请长按图片保存"),
				});
				// #endif
			},
		},
		onLoad() {
			const options = this.$Route.query
			if (this.$Route.meta.atitle) {
				uni.setNavigationBarTitle({
					title: this.$zhTran(this.$Route.meta.atitle)
				})
			}
			this.getUser().then((res) => {
				if (!res.cgp_apply) {
					setTimeout(() => {
						this.$Router.replaceAll('/pages/user/user')
					}, 200)
				} else {
					if (res.cgp_leader == 1) {
						const mode = 'all'
						const tabIndex = this.tabsList.findIndex(item => item['sign'] === mode)

						this.changeCurrentTab(tabIndex)
						setTimeout(() => {}, 0.5 * 1000)
						this.loading = false

						apiCommunityGroupPurchaseLeaderDetail().then((res) => {
							this.leaderInfo = this.$zhTran(res)
						}).catch(err => {})
					} else {
						setTimeout(() => {
							if (res.cgp_leader == 2) {
								this.$Router.replace({
									path: '/bundle2/pages/community_group_purchase/leader/be_leader',
									query: {
										...options
									}
								})
							} else {
								this.$Router.replace(
									'/bundle2/pages/community_group_purchase/leader/apply_status')
							}
						}, 200)
					}
				}
			})

		},
		onPullDownRefresh() {
			this.getUser().finally(() => {
				uni.stopPullDownRefresh();
			})
		},
	}
</script>

<style lang="scss">
	page {
		padding: 20rpx;
		box-sizing: border-box;
	}

	.leader-center {

		.leader-header {
			width: 100%;
			border-radius: 10rpx;
			overflow: hidden;
			background-color: rgba(255, 208, 0, 1);

			.top-line {
				position: relative;
				padding: 30rpx;

				.icon-avatar {
					width: 48rpx;
					height: 48rpx;
					border-radius: 50%;
					border: 1px solid #f8f8f8;
				}

				.withdraw {
					position: absolute;
					top: 30rpx;
					right: 0;
					width: 140rpx;
					color: #fff;
					padding: 10rpx 20rpx;
					font-size: 26rpx;
					background-color: rgba(250, 64, 52, 1);
					border-radius: 50rpx 0 0 50rpx;
				}
			}

			.center-num {
				text-align: center;
				padding: 10rpx 30rpx;

				.title {
					font-size: 28rpx;
				}

				.num {
					font-size: 72rpx;
					font-weight: bold;
				}
			}

			.footer-box {
				background-color: #fec803;

				.box-item {
					text-align: center;
					padding: 30rpx;
					width: calc((100% - 1rpx) / 2);

					.title {
						font-size: 24rpx;
					}

					.num {
						font-size: 32rpx;
						font-weight: bold;
					}
				}

				.line {
					width: 1rpx;
					height: 70rpx;
					background-color: #fff;
				}
			}
		}

		.order-nav {
			padding: 26rpx 0;
			background-color: #fff;
			border-radius: 10rpx;

			.nav-item {
				flex: 1;

				.badge-wrap {
					position: relative
				}
			}
		}

		.tabs-swiper {
			border-radius: 10rpx;
			overflow: hidden;
		}

		.activity-list {
			flex: 1;
			min-height: 0;
		}

		.order-contain {}

		.order {
			padding-left: 20rpx;
			margin-top: 20rpx;
			border-radius: 5px;
			padding: 30rpx;
			background-color: #FFFFFF;

			.top-item {
				position: relative;

				.title {
					font-size: 28rpx;
				}

				.date {
					color: rgba(166, 166, 166, 1);
				}

				.status {
					position: absolute;
					top: 0;
					right: -30rpx;
					width: 140rpx;
					color: #fff;
					padding: 10rpx 20rpx;
					font-size: 26rpx;
					background: linear-gradient(90deg, rgba(179, 179, 179, 1) 0%, rgba(121, 121, 121, 1) 100%);
					border-radius: 50rpx 0 0 50rpx;

					&.work {
						background: linear-gradient(90deg, rgba(254, 164, 76, 1) 0%, rgba(254, 122, 57, 1) 100%);
					}

					&.end {
						background: linear-gradient(90deg, rgba(33, 184, 71, 1) 0%, rgba(72, 175, 86, 1) 100%);
					}
				}
			}

			.goods {
				image {
					width: 25%;
				}
			}

			.share-btn {
				padding: 0 60rpx;
				background-color: rgba(255, 208, 0, 1);
				font-size: 24rpx;
			}
		}

		.verification-code {
			color: rgba(38, 38, 38, 1);
			border-radius: 10rpx;
			overflow: hidden;
			background-color: #FFFFFF;

			.title {
				font-size: 32rpx;
				font-weight: bold;
				margin: 50rpx 0;
			}

			.text {
				margin: 80rpx 30rpx;
			}

			.btns {
				&>view {
					width: 50%;
					text-align: center;
				}

				.confirm {
					background-color: rgba(255, 208, 0, 1);
				}

				.cancel {
					background-color: rgba(244, 246, 249, 1);
				}
			}
		}
	}

	.share-btns {
		&>view {
			width: calc((100% - 30rpx) / 2);
			font-size: 26rpx;
			color: rgba(34, 34, 34, 1);
			border-radius: 10rpx;
			padding: 20rpx 0;
			background-color: rgba(255, 255, 255, 1);
			text-align: center;
		}

		.saveImg {
			background-color: rgba(255, 208, 0, 1);
		}
	}
</style>